package com.zhiwang.planet.ui.jsmodule

import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import com.alipay.sdk.app.PayTask
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.planet.processor.JsModule
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.PayPresenter
import com.zhiwang.planet.mvp.v.AlipayView
import com.zhiwang.planet.mvp.v.DiamondPayView
import com.zhiwang.planet.sdkmodel.alipay.PayResult
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.my.VipRecordActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.SimpleDialogBuilder
import io.reactivex.Observable
import javax.inject.Inject

@JsModule
class MembershipModule constructor(context: BaseActivity) : BaseJsModule(context), AlipayView, DiamondPayView {


    @Inject
    lateinit var payPresenter: PayPresenter


    lateinit var bottomSheetDialog: BottomSheetDialog


    init {

        DaggerUserComponent.builder()
                .appComponent(context.getAppComponent())
                .accountModule(AccountModule(context))
                .autoDisposeModule(AutoDisposeModule(context))
                .build()
                .inject(this)
        payPresenter.aliPayView = this
        payPresenter.diamondPayView = this
    }

    @JavascriptInterface
    fun tryPayMemberShip(vipType: String, vipName: String, desc: String, userId: String) {
        context.runOnUiThread {
            showMembershipDialog(vipType, vipName, desc, userId)
        }
    }

    private fun showMembershipDialog(vipType: String, vipName: String, desc: String, userId: String) {


        //bottom vip dialog
        bottomSheetDialog = BottomSheetDialog(this)
        bottomSheetDialog.setContentView(R.layout.open_vip_layout)
        bottomSheetDialog.findViewById<TextView>(R.id.payCancel)!!.setOnClickListener {
            bottomSheetDialog.dismiss()
        }

        bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.setText(userId)
        bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.background.alpha = 0
        bottomSheetDialog.findViewById<RadioButton>(R.id.wechatpay)!!.setGone()
        bottomSheetDialog.findViewById<TextView>(R.id.vipType)!!.text = vipName
        bottomSheetDialog.findViewById<TextView>(R.id.money)!!.text = desc
        bottomSheetDialog.findViewById<TextView>(R.id.vip_target)!!.setOnClickListener {
            val tv = it as TextView
            if (tv.text == "为自己开通>>") {//切换成
                tv.text = "为好友开通>>"
                val editText = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!
                editText.setText(userId)
                //隐藏输入框灰色背景
                editText.background.alpha = 0
                editText.isEnabled = false
            } else {
                tv.text = "为自己开通>>"
                val editText = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!
                editText.background.alpha = 255
                editText.setText("")
                editText.isEnabled = true
            }
        }

        bottomSheetDialog.findViewById<TextView>(R.id.payVip)!!.setOnClickListener {
            val checkedRadioButtonId = bottomSheetDialog.findViewById<RadioGroup>(R.id.pay_group)!!.checkedRadioButtonId
            when (checkedRadioButtonId) {
                R.id.alipay -> /*getAlipaySign()*/ {
                    val userid = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.text.toString()
                    if (TextUtils.isEmpty(userid).not())
                        payPresenter.getAlipaySign(userid, vipType, "alipay_app")
                    else Toaster.message("id不能为空")
                }

//                R.id.wechatpay -> payByWechat()

                R.id.diamondpay -> {
                    val userid = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.text.toString()
                    if (TextUtils.isEmpty(userid).not())
                        payByDiamond(userid, vipType)
                    else Toaster.message("id不能为空")
                }
            }

        }
        bottomSheetDialog.show()
    }

    fun payByDiamond(userid: String, vipType: String) {
        payPresenter.payVipByDiamond(userid, vipType, "qubi")
    }

    override fun onDiamondPay() {
        //开通之后再次请求vip数据，刷新用户vip信息
        bottomSheetDialog.dismiss()

        SimpleDialogBuilder()
                .title("开通Vip")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .content("Vip开通成功")
                .build(this)
                .show()
    }


    override fun onAlipay(it: String) {
        payByAli(it)
//        tradeNo = it.tradeno
    }

    private fun payByAli(sign: String) {
        val payTask = PayTask(context)
        Observable
                .create<Map<String, String>> {
                    val result = payTask.payV2(sign, true)
                    context.runOnUiThread {
                        handlePayResult(result)
                    }
                    it.onComplete()

                }
                .androidSchedule()
                .`as`(context.androidAutoDispose())
                .subscribe({

                    //handlePayResult(it)

                }, {

                })
    }

    private fun handlePayResult(it: Map<String, String>?) {
        val payResult = PayResult(it)
        val resultInfo = payResult.result// 同步返回需要验证的信息
        val resultStatus = payResult.resultStatus
        bottomSheetDialog.dismiss()
        val msg: String
        if (TextUtils.equals(resultStatus, "9000")) {
            msg = "支付成功"
        } else if (TextUtils.equals(resultStatus, "6001")) {
            msg = "支付取消"
        } else {
            msg = "支付失败$resultStatus"
        }

        SimpleDialogBuilder()
                .title("开通VIP")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .onButtonClick(View.OnClickListener {
                    if (msg == "支付成功")
                        context.quickStartActivity(VipRecordActivity::class.java)
                })
                .content("$msg")
                .build(context)
                .show()
    }


    override fun onAuthExpired() {
        context.onAuthExpired()
    }

    override fun onError(t: Throwable) {
        context.onError(t)
    }
}